package com.tc.vms;

import com.tc.vms.config.VmsClientContext;
import com.tc.vms.config.VmsRouterManager;
import com.tc.vms.connection.VmsConnectionManager;
import com.tc.vms.exception.VmsClientException;
import com.tc.vms.iface.IContext;
import com.tc.vms.iface.VmsServiceAdaptor;
import com.tc.vms.log.VmsClientLogger;
import org.slf4j.Logger;

/**
 * Created by yonghua.zhang on 2015/12/11.
 */
public class VmsBootstrap extends VmsServiceAdaptor {
    protected final static Logger LOGGER = VmsClientLogger.getLog();
    private final VmsClientContext vmsClientContext;
    private final VmsRouterManager vmsRouterManager;
    private final VmsConnectionManager vmsConManager;

    public VmsBootstrap(VmsClientContext vmsClientContext) {
        this.vmsClientContext = vmsClientContext;
        this.vmsRouterManager = new VmsRouterManager(vmsClientContext);
        this.vmsConManager = new VmsConnectionManager(vmsRouterManager);
    }

    public VmsConnectionManager getVmsConManager() throws VmsClientException {
        if (!isOpen) throw new VmsClientException("VmsBootstrap be not initialized.");
        return vmsConManager;
    }

    @Override
    public synchronized boolean init(IContext context) throws VmsClientException {
        if (!isOpen) {
            vmsRouterManager.init(context);
            vmsConManager.init(context);
            isOpen = true;
            LOGGER.info("VmsBootstrap init successfully.");
        }
        return isOpen;
    }

    @Override
    public synchronized void shutdown() {
        if (isOpen) {
            isOpen = false;
            vmsRouterManager.shutdown();
            vmsConManager.shutdown();
        }
    }

    public VmsClientContext getVmsClientContext() {
        return vmsClientContext;
    }

    public VmsRouterManager getVmsRouterManager() throws VmsClientException {
        if (!isOpen) throw new VmsClientException("VmsBootstrap be not initialized.");
        return vmsRouterManager;
    }
}
